package com.tanhua.server.interceptor;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1:获取请求头
        String header = request.getHeader("Authorization");
        // 2:使用工具类,判断token是否有效
        /*boolean token = JwtUtils.verifyToken(header);
        if (!token){
            // 3:如果token失效,返回状态码401,进行拦截
            response.setStatus(401);
            return false;
        }*/
        // 4:如果token正常可用,放行
        // 4:1 解析token,获取id和手机号码,构造user对象,存入threadlocal
        Claims claims = JwtUtils.getClaims(header);
        String mobile = (String) claims.get("mobile");
        Integer id = (Integer) claims.get("id");

        User user = new User();
        user.setId(Long.valueOf(id));
        user.setMobile(mobile);

        UserHolder.set(user);

        return true;
    }

    /**
     * 用户使用完之后,清除掉ThreadLocal中的信息,防止内存溢出
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
